//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package upgrade

import (
	"context"
	"math"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/issue_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_dao"
)

type UpToVer9 struct{}

func (up *UpToVer9) Exec(ctx context.Context) error {
	//补全缺失的字段
	err := issue_dao.IssueDao.FixMissFieldData(ctx)
	if err != nil {
		return err
	}
	projectItemList, err := project_dao.ProjectInfoDao.ListAll(ctx, 0, math.MaxInt64)
	if err != nil {
		return err
	}
	for _, projectItem := range projectItemList {
		err = up.fixDependMeCount(ctx, projectItem.ProjectId)
		if err != nil {
			return err
		}
	}
	return dao.VersionDao.Set(ctx, dao.VERSION_KEY_SCHEMA, 9)
}

func (up *UpToVer9) fixDependMeCount(ctx context.Context, projectId string) error {
	dependIssueIdList, err := issue_dao.DependDao.DistinctAllDependIssueId(ctx, projectId)
	if err != nil {
		return err
	}
	for _, dependIssueId := range dependIssueIdList {
		issueIdList, err := issue_dao.DependDao.DistinctByDependIssue(ctx, projectId, dependIssueId)
		if err != nil {
			return err
		}
		issue_dao.IssueDao.UpdateDependMeCount(ctx, projectId, dependIssueId, len(issueIdList))
	}
	return nil
}
